package javabasic.threads.CreateThreadMethods;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 通过实现callable接口创建子线程，可以获取子线程返回值，但是需要依赖futureTask类
 */
public class Method03Callable {
    public static void main(String[] args) {
        FutureTask<Integer> integerFutureTask = new FutureTask<Integer>(new CallableTest(0));
        Thread myThread = new Thread(integerFutureTask);
        myThread.start();
        while (!integerFutureTask.isDone()){
            System.out.println("子线程还未执行完毕，请等待。。。。。。");
        }
        try {
            Integer res = integerFutureTask.get();
            System.out.println("子线程执行完毕");
            System.out.println(res);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
class CallableTest implements Callable{
    private int sum;

    public CallableTest(int sum) {
        this.sum = sum;
    }

    @Override
    public Object call() throws Exception {
        for (int i = 0; i < 10; i++) {
            this.sum+=i;
            Thread.sleep(100);
        }
        return this.sum;
    }
}
